<template>
  <div class="app-container">
    <div class="jcxx">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>基础信息</span>
        </div>
        <div class="text item">
          <div>
            <el-form ref="PyInbound" :model="pyInboundData" :rules="rules" size="small" label-width="100px"
              label-position="left">
              <el-row type="flex" justify="space-around" align="bottom">
                <el-col :span="10">
                  <el-form-item label="入库单号" prop="inventoryNumber">
                    <el-input v-model="pyInboundData.inventoryNumber" placeholder="自动获取系统编号" :disabled='true'
                      :style="{ width: '100%' }"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="入库类型" prop="inventoryType">
                    <el-select v-model="pyInboundData.inventoryType" placeholder="请选择入库类型" clearable
                      @change="handleInventoryTypeChange" :style="{ width: '100%' }">
                      <el-option v-for="dict in dict.type.py_instock_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row type="flex" justify="space-around" align="bottom">
                <el-col :span="10">
                  <el-form-item label="仓库名称" prop="warehouseId">
                    <el-select v-model="pyInboundData.warehouseId" placeholder="请选择" @change="onWarehouseChange"
                      :style="{ width: '100%' }">
                      <el-option v-for="item in warehouseIds" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="入库日期" prop="inboundDate">
                    <el-date-picker v-model="pyInboundData.inboundDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                      :style="{ width: '100%' }" placeholder="请选择"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row type="flex" justify="space-around" align="bottom">
                <el-col :span="10">
                  <el-form-item label="关联单号" prop="relatedNumber">
                    <div style="display: flex; align-items: center;">

                      <el-input v-model="pyInboundData.relatedNumber" placeholder="请输入" :style="{ width: '100%' }"
                        :disabled="linkPurchaseOrder">
                      </el-input>
                      <el-button style="padding-left: 10px;" v-if="linkPurchaseOrder" @click="openOrderSelection"
                        type="text">查看</el-button>
                      <el-checkbox style="padding-left: 10px;" v-model="linkPurchaseOrder"
                        @change="handleCheckboxChange">关联单号</el-checkbox>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <!-- <el-form-item v-if="this.pyInboundData.inventoryType==null" label="供应商" prop="supplierId">
                    <el-select v-model="pyInboundData.supplierId" placeholder="请选择" :disabled="linkPurchaseOrder"
                      @change="fetchSupplierContact" :style="{ width: '100%' }">
                      <el-option v-for="item in supplierIds" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item> -->
                  <el-form-item
                    v-if="this.pyInboundData.inventoryType === '0' || this.pyInboundData.inventoryType == null"
                    label="供应商" prop="supplierId">
                    <el-select v-model="pyInboundData.supplierId" placeholder="请选择" :disabled="linkPurchaseOrder"
                      @change="fetchSupplierContact" :style="{ width: '100%' }">
                      <el-option v-for="item in supplierIds" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item v-if="this.pyInboundData.inventoryType === '1'" label="客户名称" prop="customer">
                    <el-input v-model="pyInboundData.customer" placeholder="请输入客户名称" :disabled=true
                      :style="{ width: '100%' }">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row type="flex" justify="space-around" align="bottom">
                <el-col :span="10">
                  <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="pyInboundData.contactPerson" placeholder="请输入联系人" :disabled=true
                      :style="{ width: '100%' }">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="联系方式" prop="contactPhone">
                    <el-input v-model="pyInboundData.contactPhone" placeholder="请输入" :disabled=true
                      :style="{ width: '100%' }"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10" style="margin-left: 70px;padding-left: 5px;">
                  <!-- <el-form-item label="经办人">
                    <el-cascader v-model="pyInboundData.handler" :options="cascaderOptions" :props="cascaderProps"
                      placeholder="请选择" @change="handleChange" :style="{ width: '100%' }" />
                  </el-form-item> -->
                  <el-form-item label="经办人">
                    <treeselect v-model="pyInboundData.handler" :options="deptOptions" :show-count="true"
                      :style="{ width: '100%' }" placeholder="请选择归属部门" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row style="margin-left: 70px; padding-left: 7px;">
                <el-form-item label=" 备注" prop="remarks">
                <el-input v-model="pyInboundData.remarks" type="textarea" placeholder="请输入" :maxlength="1000"
                  :autosize="{ minRows: 4, maxRows: 10 }" :style="{ width: '100%' }"></el-input>
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </div>
      </el-card>
      <!-- 选择进货单 -->
      <el-dialog title="选择进货单" :visible.sync="openPurchaseOrder">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item>
            <el-input v-model="queryParams.phCode" placeholder="请输入进货单号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.phState" placeholder="请选择单据状态" clearable>
              <el-option v-for="dict in dict.type.py_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryParams.supplierId" placeholder="请选择供应商">
              <el-option v-for="item in supplierIds" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker clearable v-model="queryParams.phDate" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择进货日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="JHDDhandleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="JHDDresetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="table" v-loading="loading" :data="purchaseList" @selection-change="JHDDhandleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="phId" />
          <el-table-column width="150" label="进货单号" align="center" prop="phCode" />
          <el-table-column label="单据状态" align="center" prop="phState">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.py_status" :value="scope.row.phState" />
            </template>
          </el-table-column>
          <el-table-column label="进货日期" align="center" prop="phDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.phDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column width="120" label="供应商" align="center" prop="supplierName" />
          <el-table-column width="120" label="进货部门" align="center" prop="deptName" />
          <el-table-column width="120" label="进货人" align="center" prop="phPerson" />
          <el-table-column width="120" label="货品数量" align="center" prop="goodsNum" />
          <el-table-column width="100" label="货品金额" align="center" prop="goodsMoney">
            <template slot-scope="scope">
              {{ fun(scope.row.goodsMoney) }}
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="JHDDgetList" />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="JHDDsubmitForm">确 定</el-button>
          <el-button @click="JHDDcancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 选择退货单 -->
      <el-dialog title="选择退货单" :visible.sync="openReturnOrder">
        <el-form :model="XZTHqueryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item>
            <el-input v-model="XZTHqueryParams.srCode" placeholder="请输入退货单号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="XZTHqueryParams.srState" placeholder="请选择单据状态" clearable>
              <el-option v-for="dict in dict.type.py_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker clearable v-model="XZTHqueryParams.saleDate" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择退货日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="JHTHhandleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="JHTHresetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="table" v-loading="loading" :data="returnList" @selection-change="JHDDhandleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="srId" />
          <el-table-column width="150" label="退货单号" align="center" prop="srCode" />
          <el-table-column label="单据状态" align="center" prop="srState">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.py_status" :value="scope.row.srState" />
            </template>
          </el-table-column>
          <el-table-column label="销售日期" align="center" prop="saleDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户名称" align="center" prop="customer" />
          <el-table-column label="销售部门" align="center" prop="saleDept" />
          <el-table-column width="120" label="销售负责人" align="center" prop="salePerson" />
          <el-table-column label="退货数量" align="center" prop="rejectedNum" />
          <el-table-column width="100" label="退货金额" align="center" prop="rejectedMoney">
            <template slot-scope="scope">
              {{ fun(scope.row.rejectedMoney) }}
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="THtotal > 0" :total="THtotal" :page.sync="XZTHqueryParams.pageNum"
          :limit.sync="XZTHqueryParams.pageSize" @pagination="handleReturnStock" />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="THsubmitForm">确 定</el-button>
          <el-button @click="JHDDcancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>入库明细</span>
        </div>
        <!-- <span></span> -->
        <div class="text item">
          <span>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="RKMXopenDialog">添加</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="">删除</el-button>
            <!-- <el-button type="success" @click="">添加</el-button>
            <el-button type="danger">移除</el-button> -->
          </span>
        </div>
        <!-- //添加进货入库明细 -->
        <el-dialog title="添加货品" style="width: 100%" :visible.sync="openInventoryDetails">
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple-dark" style="margin-top: -30px;padding-left: 10px;">
                <span> 进货单号：{{ this.pyInboundData.inventoryNumber }}</span>
                <!-- <span> 进货日期：{{ inboundDate }}</span>
                <span> 供应商：{{ supplier }}</span>
                <span> 金额：{{ totalAmount }}</span>
                <span> 数量：{{ totalQuantity }}</span>  -->
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple-dark">
                <el-form :model="JHMXqueryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
                  <el-form-item>
                    <el-input v-model="JHMXqueryParams.productCode" placeholder="请输入货品编号名称" clearable
                      @keyup.enter.native="handleQuery" />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="RKMXhandleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="RKMXresetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
          <el-table ref="table" :data="filteredProducts" @selection-change="JHMXhandleSelectionChange" border>
            <el-table-column width="55" align="center">
              <template slot-scope="scope">
                <!-- 已添加的货品显示绿色对勾 -->
                <span v-if="addedItemCodes.has(scope.row.productCode)" style="color: #67c23a">
                  <i class="el-icon-check"></i>
                </span>
                <!-- 未添加的货品显示复选框 -->
                <el-checkbox v-else v-model="scope.row.isSelected"
                  @change="(val) => handleSingleSelect(val, scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="phDetailsId" label="序号" width="55"></el-table-column>
            <el-table-column prop="productCode" label="货品编号" width="160"></el-table-column>
            <el-table-column prop="productName" label="货品名称" width="120"></el-table-column>
            <el-table-column prop="productModel" label="规格型号" width="120"></el-table-column>
            <el-table-column prop="unit" label="单位" width="90">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.py_product_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column prop="inboundPrice" label="进货单价" width="120">
              <template slot-scope="scope">
                {{ fun(scope.row.inboundPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="productNum" label="进货数量" width="120"></el-table-column>
            <el-table-column prop="inboundAmount" label="进货金额" width="120">
              <template slot-scope="scope">
                {{ fun(scope.row.inboundAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="alreadyNum" label="已入库" width="90"></el-table-column>
            <el-table-column prop="notStocked" label="未入库" width="90"></el-table-column>
          </el-table>
          <pagination v-show="MXtotal > 0" :total="MXtotal" :page.sync="JHMXqueryParams.pageNum"
            :limit.sync="JHMXqueryParams.pageSize" @pagination="OdPurchaseDetails" />
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="RKMXsubmitForm">确 定</el-button>
            <el-button @click="openInventoryDetails = false">取 消</el-button>
          </div>
        </el-dialog>

        <!-- //添加退货入库明细 -->
        <el-dialog title="添加货品" style="width: 100%" :visible.sync="openReturnInventoryDetails">
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple-dark" style="margin-top: -30px; padding-left: 20px;">
                <span>退货单号：{{ this.pyInboundData.inventoryNumber }}</span>
                <!-- <span>进货日期：{{ inboundDate }}</span>
                <span>供应商：{{ supplier }}</span>
                <span>金额：{{ totalAmount }}</span>
                <span>数量：{{ totalQuantity }}</span> -->
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple-dark">
                <el-form :model="THMXqueryParams" ref="returnQueryForm" size="small" :inline="true" label-width="68px">
                  <el-form-item>
                    <el-input v-model="THMXqueryParams.productCode" placeholder="请输入货品编号名称" clearable
                      @keyup.enter.native="handleReturnQuery" />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="THMXhandleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="THMXhresetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
          <el-table ref="returnTable" :data="filteredReturnProducts" @selection-change="THMXhandleSelectionChange"
            border>
            <el-table-column width="55" align="center">
              <template slot-scope="scope">
                <!-- 已添加的货品显示绿色对勾 -->
                <span v-if="addedItemCodes.has(scope.row.productCode)" style="color: #67c23a">
                  <i class="el-icon-check"></i>
                </span>
                <!-- 未添加的货品显示复选框 -->
                <el-checkbox v-else v-model="scope.row.isSelected"
                  @change="(val) => handleSingleSelect(val, scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="srDetailsId" label="序号" width="55"></el-table-column>
            <el-table-column prop="productCode" label="货品编号" width="160"></el-table-column>
            <el-table-column prop="productName" label="货品名称" width="120"></el-table-column>
            <el-table-column prop="productModel" label="规格型号" width="120"></el-table-column>
            <el-table-column prop="unit" label="单位" width="90">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.py_product_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column prop="salePrice" label="退货单价" width="120">
              <template slot-scope="scope">
                {{ fun(scope.row.salePrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="rejectedNum" label="退货数量" width="120"></el-table-column>
            <el-table-column prop="rejectedPrice" label="退货金额" width="120">
              <template slot-scope="scope">
                {{ fun(scope.row.rejectedPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="alreadyNum" label="已入库" width="90"></el-table-column>
            <el-table-column prop="notStocked" label="未入库" width="90"></el-table-column>
          </el-table>
          <pagination v-show="MXTHtotal > 0" :total="MXTHtotal" :page.sync="JHMXqueryParams.pageNum"
            :limit.sync="JHMXqueryParams.pageSize" @pagination="RejectedDetailsList" />

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="THMXsubmitForm">确 定</el-button>
            <el-button @click="openReturnInventoryDetails = false">取 消</el-button>
          </div>
        </el-dialog>


        <div class="text item">
          <el-table ref="table" :data="RKMXtableData" style="width: 100%" @selection-change="RKMXhandleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <!-- <template v-if="this.pyInboundData.inventoryType === '0'"> -->
            <el-table-column fixed prop="phDetailsId" label="序号" width="50"></el-table-column>
            <!-- </template> -->
            <!-- <template v-else> -->
            <!-- <el-table-column fixed prop="rdId" label="序号" width="50"></el-table-column> -->
            <!-- </template> -->
            <el-table-column fixed prop="productName" label="货品名称" width="120"></el-table-column>
            <el-table-column fixed prop="productCode" label="货品编号" width="120"></el-table-column>
            <el-table-column prop="productType" label="货品类型" width="100"></el-table-column>
            <el-table-column prop="productModel" label="规格型号" width="100"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.py_product_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column prop="currentStock" label="当前库存" width="100"></el-table-column>
            <template v-if="this.pyInboundData.inventoryType === '0'">
              <el-table-column prop="productNum" label="进货数量" width="100"></el-table-column>
            </template>
            <template v-else>
              <el-table-column prop="rejectedNum" label="退货数量" width="100"></el-table-column>
            </template>
            <template v-if="linkPurchaseOrder">
              <el-table-column prop="alreadyNum" label="已入库数量" width="100"></el-table-column>
            </template>
            <template v-if="linkPurchaseOrder">
              <el-table-column prop="notStocked" label="未入库数量" width="100"></el-table-column>
            </template>
            <!-- 库位选择下拉框 -->
            <el-table-column label="入库库位" width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.locationCode" placeholder="请选择"
                  @change="(value) => fetchwhLocationContact(value, scope.row.productCode, scope.row)">
                  <el-option v-for="item in whLocation" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>

            <!-- 本次入库数量输入框 -->
            <el-table-column label="本次入库数量" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.quantityThisTime" placeholder="请输入数量"
                  @blur="validateQuantity(scope.row)"></el-input>
              </template>
            </el-table-column>
            <template v-if="this.pyInboundData.inventoryType === '0'">
              <el-table-column prop="inboundPrice" label="进货单价" width="120">
                <template slot-scope="scope">
                  {{ fun(scope.row.inboundPrice) }}
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column prop="salePrice" label="入库单价" width="120">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.salePrice" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
            </template>



            <!-- 入库金额 -->
            <el-table-column v-if="this.pyInboundData.inventoryType === '0'" prop="inboundAmount" label="进货金额"
              width="120">
              <template slot-scope="scope">
                {{ fun(scope.row.inboundAmount) }}
              </template>
            </el-table-column>

            <el-table-column v-if="this.pyInboundData.inventoryType === '1'" label="入库金额" width="120">
              <template slot-scope="scope">
                <span>{{ ((scope.row.quantityThisTime || 0) * (scope.row.salePrice || 0)).toFixed(2) }}</span>
                <!-- 计算入库金额并保留两位小数 -->
              </template>
            </el-table-column>
            <!-- 批次号输入框 -->
            <el-table-column label="批次号" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.batchNumber" placeholder="请输入批次号"></el-input>
              </template>
            </el-table-column>

            <!-- 生产日期日期选择框 -->
            <el-table-column label="生产日期" width="150">
              <template slot-scope="scope">
                <el-date-picker v-model="scope.row.productionDate" type="date" placeholder="选择日期" style="width: 100%;">
                </el-date-picker>
              </template>
            </el-table-column>
            <!-- 备注输入框 -->
            <el-table-column label="备注" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template slot-scope="scope">
                <el-button @click.native.prevent="deleteRow(scope.row)" type="text" size="small">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>


          <tr class="total-row">
            <td>合计</td>
            <span class="you">
              <td>
                <span class="label">未入库数量:</span>
                <span class="value">{{ totalCurrentStock }}</span>
              </td>
              <td>
                <span class="label">已入库数量:</span>
                <span class="value">{{ totalIncomingQuantity }}</span>
              </td>
              <td>
                <span class="label">入库种类:</span>
                <span class="value">{{ totalInStockQuantity }}</span>
              </td>
              <td>
                <span class="label">入库数量:</span>
                <span class="value">{{ totalNotStockQuantity }}</span>
              </td>
              <td>
                <span class="label">入库金额:</span>
                <span class="value">{{ totalNotStockAmount.toFixed(2) }}</span>
              </td>
            </span>

          </tr>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>上传附件</span>
        </div>
        <div class="text item">
          <el-upload class="upload-demo" :action="uploadImgUrl" :on-change="uploadChange" :file-list="fileList"
            :before-upload="beforeUpload" :headers="headers">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持上传doc, pdf, rar等格式，单个文件最大200MB</div>
          </el-upload>
        </div>
      </el-card>
      <el-footer class="fixed-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">关闭</el-button>
        <!-- <el-button>保存并提交</el-button> -->
      </el-footer>
    </div>
  </div>
</template>
<script>
import {
  getCode, selectAllSysDept, selectAllSysDeptByID, selectAllSysUserByParentId, listRejected, selectOdSaleRejectedDetailsList, deptTreeSelect,
  selectAllPySuppliers, selectAllBsWarehouse, selectSuppliersByid, selectAllOdPurchaseOrder, selectOdRejectedDetails,
  selectAllOdPurchaseDetails, selectWhInventoryByCode, selectAllBsWhLocation, adddetalis, addInbound, getInbound, updateInbound, updateInboundDetalis
} from "@/api/inbound/inbound";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  dicts: ['py_status', 'py_instock_type', 'py_product_unit'],
  components: { Treeselect },
  props: [],
  data() {
    return {
      deptOptions: undefined,
      isClick: true,
      total: 0,
      THtotal: 0,
      MXtotal: 0,
      MXTHtotal: 0,
      addedItemCodes: new Set(), // 用于跟踪已添加的货品编号
      selectedItems: new Set(), // 新增：用于临时存储新选择的货品
      THselectList: [],
      // 进货遮罩层
      loading: false,
      gysid: null,
      phCodes: [],
      jbr: [],
      phsupplierIds: [],//进货单号选中的供应商id
      openPurchaseOrder: false,//选择进货订单弹出框
      openReturnOrder: false,//选择退货订单弹出框
      RKMXtableData: [],     // 存储入库列表数据
      openReturnInventoryDetails: false,//添加退货入库明细弹出框
      //进货订单查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phCode: null,
        phState: null,
        phDate: null,
      },
      XZTHqueryParams: {
        pageNum: 1,
        pageSize: 10,
        srCode: null,
        srState: null,
        saleDate: null,
      },
      JHMXqueryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        phCodes: null
      },
      THMXqueryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: '',
        srCode: ''
      },
      // 进货订单表格数据
      purchaseList: [
        { supplierId: null }

      ],
      returnList: [],
      openInventoryDetails: false,//添加进货入库明细弹出框
      warehouseIds: [],//仓库名称id数组
      supplierIds: [],//供应商id数组
      whLocation: [],//库位下拉
      tableKey: 0, // 用于强制刷新表格的 key
      cascaderOptions: [],
      cascaderProps: {
        value: 'value',
        label: 'label',
        children: 'children',
        // checkStrictly: true
      },
      linkPurchaseOrder: true,
      pyInboundData: {
        inventoryId: undefined,
        inventoryNumber: undefined,
        inventoryType: undefined,//入库类型
        warehouseId: undefined,//仓库名称id
        inboundDate: undefined,
        relatedNumber: undefined,
        supplierId: undefined,
        contactPerson: undefined,
        contactPhone: undefined,
        remarks: undefined,
        handler: undefined,
        number: undefined,
        codeId: undefined,
        status: undefined,
        fileList: [],
        PyInboundDetalisList: []
      },
      //进货入库明细表格
      filteredProducts: [],
      //退货入库明细表格
      filteredReturnProducts: [],
      selectedProducts: [],
      selectedProductIds: [],
      rules: {
        inventoryNumber: [
          { required: true, message: '请输入入库单号', trigger: 'blur' }
        ],
        inventoryType: [
          { required: true, message: '请选择入库类型', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择仓库名称', trigger: 'change' }
        ],
        inboundDate: [
          { required: true, message: '请选择入库日期', trigger: 'change' }
        ],
        relatedNumber: [
          { required: true, message: '请输入单号', trigger: 'blur' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        handler: [
          { required: true, message: '请选择经办人', trigger: 'change' }
        ]
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [], // 已上传的文件列表
    }
  },
  computed: {
    totalCurrentStock() {
      return this.RKMXtableData.reduce((total, item) => total + item.notStocked, 0);
    },
    totalIncomingQuantity() {
      return this.RKMXtableData.reduce((total, item) => total + item.alreadyNum, 0);
    },
    totalInStockQuantity() {
      const productTypes = new Set(this.RKMXtableData.map(item => item.productType));
      return productTypes.size; // 返回独特货品类型的数量
    },
    totalNotStockQuantity() {
      return this.RKMXtableData.reduce((total, item) => {
        // 检查 quantityThisTime 是否为有效数字
        const quantity = item.quantityThisTime ? Number(item.quantityThisTime) : 0;
        return total + quantity;
      }, 0);
    },
    totalNotStockAmount() {
      return this.RKMXtableData.reduce((total, item) => {
        // 检查 quantityThisTime 是否为有效数字
        const quantity = item.quantityThisTime ? Number(item.quantityThisTime) : 0;

        // 根据入库类型选择价格
        let price = 0;
        if (this.pyInboundData.inventoryType === '0') {
          price = item.inboundPrice ? Number(item.inboundPrice) : 0; // 进货单价
        } else if (this.pyInboundData.inventoryType === '1') {
          price = item.salePrice ? Number(item.salePrice) : 0; // 入库单价
        }

        return total + (quantity * price);
      }, 0);
    }
  },

  created() {
    this.getDeptTree();
    // 确保selectAllBsWarehouse是一个函数并调用它
    selectAllBsWarehouse().then(response => {
      this.warehouseIds = response.data.map(item => ({
        value: item.warehouseId,
        label: item.warehouseName
      }));
    }).catch(error => {
      console.error('Fetching warehouses failed:', error);
    });

    selectAllPySuppliers()
      .then(response => {
        this.supplierIds = response.data.map(item => ({
          value: item.supplierId,
          label: item.supplierName
        }));
      }).catch(error => {
        console.error('Fetching suppliers failed:', error);
      });
    const inventoryId = this.$route.query.id;
    if (inventoryId == null) {
      getCode(2).then(response => {
        this.pyInboundData.inventoryNumber = response.sequence;
        this.pyInboundData.number = response.number;
        this.pyInboundData.codeId = response.codeId;
      });
    } else {
      getInbound(inventoryId)
        .then(response => {
          // 确保在设置后调用 onWarehouseChange
          console.log('获取修改信息:', JSON.stringify(response.data, null, 2));
          console.log('联系方式:', response.data.pyInbound.contactNumber);
          console.log('入库单价:', response.data.pyInboundDetalis[0].inboundPrice);
          this.pyInboundData = response.data.pyInbound;
          this.RKMXtableData = response.data.pyInboundDetalis;
          this.RKMXtableData.forEach(item => {
            item.alreadyNum = item.quantityReceived; // 将 quantityReceived 映射到 alreadyNum
            item.notStocked = item.quantityPending; // 将 quantityPending 映射到 notStocked
            item.productName = item.productNames; // 确保 productName 的赋值
            item.productType = item.productTypeName; // 确保 productType 的赋值
            item.locationCode = item.locationCode;
            item.unit = item.productUnit;
            item.salePrice = item.inboundPrice;
          });
          // this.$set(this.pyInboundData, "handler", response.data.pyInbound.handler);
          this.pyInboundData.inventoryType = String(this.pyInboundData.inventoryType);
          this.pyInboundData.contactPhone = response.data.pyInbound.contactNumber;
          this.pyInboundData.handler = response.data.pyInbound.handler+10
          console.log('经办人:' + this.pyInboundData.handler);
          // 合并新旧文件列表
          this.fileList = [...response.data.pyInbound.fileList.flat().map(file => ({
            name: file.fileName,
            url: file.filePath,
            size: file.size
          })), ...this.fileList];
          // this.pyInboundData.warehouseId = this.pyInboundData.warehouseId;
          // // 更新联系人的电话
          // this.pyInboundData.contactPerson = response.data.contactPerson || ''; // 确保是字符串
          // this.pyInboundData.contactPhone = response.data.contactPhone || ''; // 确保是字符串
          // 初始化库位和当前库存

          // 调用以获取对应的库位信息
          if (this.pyInboundData.warehouseId) {
            this.onWarehouseChange();
          }
        })
        .catch(error => {
          console.error('获取修改信息:', error);
        });
    }
    this.fetchItems();

  },
  methods: {
    rest() {
      this.pyInboundData = {
        inventoryNumber: '',
        inventoryType: undefined,
        warehouseId: '',
        inboundDate: '',
        relatedNumber: '',
        supplierId: '',
        contactPerson: '',
        contactPhone: '',
        handler: '',
        number: undefined,
        codeId: undefined,
        remarks: '',
        RKMXtableData: [],
        fileList: []
      }
      this.resetForm("PyInbound");
    },
    //修改关闭
    cancel() {
      this.$emit('update:visible', false);
      this.rest();
      this.$router.push({ path: '/inout/inbound' });
    },
    //金额保留2位数
    fun(val) {
      return Number(val).toFixed(2);
    },
    //选中供应商自动获取联系人和电话
    fetchSupplierContact(selectedSupplierId) {
      selectSuppliersByid(selectedSupplierId)
        .then(response => {
          console.log('获取联系人:', JSON.stringify(response, null, 2));
          // 更新联系人的电话
          this.pyInboundData.contactPerson = response.data.contactPerson || ''; // 确保是字符串
          this.pyInboundData.contactPhone = response.data.contactPhone || ''; // 确保是字符串
        })
        .catch(error => {
          console.error('获取联系人信息失败:', error);
        });
    },
    //保存
    submitForm() {
      this.$refs.PyInbound.validate((valid) => {
        if (!this.isClick) {
          this.$message.warning("请勿重复提交")
          return;
        }
        this.isClick = false;
        if (valid) {
          for (let row of this.RKMXtableData) {
            if (!row.locationCode) {
              this.$message.error('请选择入库库位！');
              this.isClick = true;
              return;
            }
            if (!row.quantityThisTime) {
              this.$message.error('本次入库数量不能为空！');
              this.isClick = true;
              return;
            }
            if (!row.batchNumber) {
              this.$message.error('批次号不能为空！');
              this.isClick = true;
              return;
            }
            if (!row.productionDate) {
              this.$message.error('生产日期不能为空！');
              this.isClick = true;
              return;
            }
          }
          // 表单验证通过，处理表单提交
          const inventoryId = this.pyInboundData.inventoryId; // 直接获取 inventoryId
          // 在 RKMXtableData 中添加 inventoryNumber
          this.RKMXtableData.forEach(item => {
            item.inventoryNumber = this.pyInboundData.inventoryNumber;
            item.phCode = this.pyInboundData.relatedNumber;
            item.quantityPending = item.notStocked;
          });

          if (!inventoryId) { // 判断 inventoryId 是否有效
            console.log('表单验证通过，提交数据:', this.pyInboundData);
            console.log('入库编号:', this.pyInboundData.inventoryNumber);
            console.log('表单验证通过，提交数据2:', this.RKMXtableData);
            this.pyInboundData.fileList = this.fileList
            if (typeof this.pyInboundData.handler === 'number') {
              this.pyInboundData.handler -= 10;
            }
            // this.pyInboundData.handler = this.pyInboundData.handler - 10;
            this.pyInboundData.PyInboundDetalisList = this.RKMXtableData;
            // 新增操作
            const payload = {
              ...this.pyInboundData,
              pyInboundDetalisList: this.RKMXtableData,
            };
            addInbound(payload).then(response => {
              console.log('新增后端响应:', JSON.stringify(response, null, 2));

              // 检查返回的响应是否是警告
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功");
                this.$router.push({ path: '/wms/inbound/inbounds/find' });
                this.isClick = true;
              } else if (response.code === 601) { // 假设 400 代表警告
                this.isClick = true;
                this.$msgbox({
                  title: '提示',
                  message: response.msg,
                  type: 'warning',
                  showCancelButton: false,
                  confirmButtonText: '知道了',

                  // 任何其他需要的设置
                }).then(() => {

                  // 可以添加点击确认后的操作
                }).catch(() => {
                  // 可以添加点击取消后的操作（如果启用取消按钮）
                });
              }
            }).catch(error => {
              console.error('新增入库操作失败:', error);
              // this.$message.error('新增入库操作失败: ' + error.message); // 提示用户
            });
            // addInbound(payload).then(response => {
            //   console.log('新增后端响应:', JSON.stringify(response, null, 2));
            //   // if (response.code === 200) {
            //   //   // return adddetalis(this.RKMXtableData); // 继续处理明细
            //   // } else {
            //   //   throw new Error('新增操作失败，错误码: ' + response.code);
            //   // }
            // }).then(response => {
            //   console.log('新增明细后端响应:', JSON.stringify(response, null, 2));
            //   this.$modal.msgSuccess("新增成功");
            //   this.$router.push({ path: '/wms/inbound/inbounds/find' });
            //   // this.getList();  // 准备数据
            // }).catch(error => {
            //   console.error('新增入库操作失败:', error);
            //   this.$message.error('新增入库操作失败: ' + error.message); // 提示用户
            // });
          } else {
            // 修改操作
            this.pyInboundData.status = 0; // 设置状态
            this.pyInboundData.fileList = this.fileList
            this.pyInboundData.handler = this.jbr[this.jbr.length - 1];
            console.log('表单验证通过，提交数据:', this.pyInboundData);
            console.log('列表:', this.fileList);
            console.log('表单验证通过，提交数据2:', this.RKMXtableData);
            updateInbound(this.pyInboundData).then(response => {
              console.log('修改后端响应:', JSON.stringify(response, null, 2));
              if (response.code === 200) {
                this.isClick = true;
                return updateInboundDetalis(this.RKMXtableData); // 继续处理明细
              } else {
                throw new Error('修改操作失败，错误码: ' + response.code);
              }
            }).then(response => {
              this.isClick = true;
              console.log('修改明细后端响应:', JSON.stringify(response, null, 2));
              this.$modal.msgSuccess("修改成功");
              this.$router.push({ path: '/wms/inbound/inbounds/find' });
            }).catch(error => {
              this.isClick = true;
              console.error('更新入库操作失败:', error);
              this.$message.error('更新入库操作失败: ' + error.message); // 提示用户
            });
          }
        } else {
          this.isClick = true;
          // 表单验证失败，提示用户
          console.log('表单验证失败，请检查输入');
          return false;
        }
      });
    },


    async onWarehouseChange() {
      // const inventoryId = this.$route.query.id;
      // if (inventoryId == null) {
      const warehouseId = this.pyInboundData.warehouseId;


      // 尝试将 warehouseId 转换为数字
      const warehouseIdLong = Number(warehouseId);
      console.log("转换后的仓库ID:", warehouseIdLong);

      if (!isNaN(warehouseIdLong) && warehouseIdLong > 0) { // 检查转换结果是否有效
        try {
          // 调用封装的方法获取对应的库存信息
          const response = await selectAllBsWhLocation(warehouseIdLong);
          this.whLocation = response.data.map(item => ({
            value: item.locationCode,
            label: item.locationName
          }));
          // this.updateTableData(); // 更新表格数据
          // 在这里触发库存查询
          for (const item of this.RKMXtableData) {
            if (item.locationCode) {
              this.fetchwhLocationContact(item.locationCode, item.productCode, item);
            }
          }
        } catch (error) {
          console.error('获取库位信息失败:', error);
          // 在这里可以提示用户失败信息
        }
      } else {
        console.error("无效的仓库ID:" + warehouseId);
        this.whLocation = []; // 如果没有选择仓库，则重置库位

      }
    },
    async fetchItems() {
      try {
        const response = await selectAllSysDept();
        if (Array.isArray(response)) {
          this.cascaderOptions = await this.convertToCascaderOptions(response);
        } else {
          console.error('Expected an array, but got:', response);
        }
      } catch (error) {
        console.error('Error fetching items:', error);
      }
    },

    async convertToCascaderOptions(data) {
      if (!Array.isArray(data)) {
        console.error('Expected an array, but got:', data);
        return [];
      }

      // 创建一个映射，用于快速查找父项
      const itemMap = new Map(data.map(item => [item.deptId, item]));
      const topLevelItems = [];

      for (const item of data) {
        if (item.parentId === 0) {
          topLevelItems.push(await this.createOption(item));
        } else {
          const parentItem = itemMap.get(item.parentId);
          if (parentItem) {
            const childItem = await this.createOption(item);
            if (!parentItem.children) {
              parentItem.children = [];
            }
            parentItem.children.push(childItem);
          }
        }
      }

      return topLevelItems;
    },

    async createOption(item) {
      const [children, users] = await Promise.all([
        this.fetchChildren(item.deptId),
        this.fetchUsers(item.deptId)
      ]);
      return {
        value: item.deptId,
        label: item.deptName,
        children: children,
        users: users
      };
    },

    async fetchUsers(deptId) {
      try {
        const response = await selectAllSysUserByParentId(deptId);
        if (Array.isArray(response)) {
          return response.map(user => ({
            value: user.userId,
            label: user.userName
          }));
        } else {
          console.error('Expected an array, but got:', response);
          return [];
        }
      } catch (error) {
        console.error('Error fetching users:', error);
        return [];
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        console.log('后端响应:' + JSON.stringify(response.data, null, 2));
        this.deptOptions = response.data;
      });
    },
    async fetchChildren(parentId) {
      try {
        const response = await selectAllSysDeptByID(parentId);
        if (Array.isArray(response)) {
          return Promise.all(response.map(async (item) => {
            const [users, children] = await Promise.all([
              this.fetchUsers(item.deptId),
              this.fetchChildren(item.deptId) // 递归获取子部门
            ]);
            return {
              value: item.deptId,
              label: item.deptName,
              children: [
                ...children,
                ...users.map(user => ({
                  value: user.value,
                  label: user.label,
                  // isUser: true
                }))
              ]
            };
          }));
        } else {
          console.error('Expected an array, but got:', response);
          return [];
        }
      } catch (error) {
        console.error('Error fetching children:', error);
        return [];
      }
    },
    handleChange(value) {
      // const currentSelectedValue = value[value.length - 1];
      this.jbr = value;
      console.log('后端响应:', value);
    },

    openOrderSelection() {
      if (this.pyInboundData.inventoryType === '0') {
        this.openPurchaseOrder = true
        this.JHDDgetList(); // 进货入库逻辑
      } else if (this.pyInboundData.inventoryType === '1') {
        this.openReturnOrder = true;
        this.handleReturnStock(); // 退货入库逻辑
      }
    },
    JHDDgetList() {
      selectAllOdPurchaseOrder(this.queryParams)
        .then(response => {
          // // 使用 JSON.stringify 转换并美化输出
          console.log('后端响应11:', JSON.stringify(response, null, 2));

          // 假设 response.data 是一个数组，包含多个进货单信息
          this.purchaseList = response.rows.map(item => ({
            phId: item.phId,
            phCode: item.phCode,
            phState: item.phState,
            phDate: item.phDate,
            supplierName: item.pySuppliers ? item.pySuppliers.supplierName : '', // 供应商名称
            supplierId: item.pySuppliers ? item.pySuppliers.supplierId : '',
            deptName: item.sysDept ? item.sysDept.deptName : '', // 进货部门名称
            phPerson: item.phPerson, // 进货人
            goodsNum: item.goodsNum, // 货品数量
            goodsMoney: item.goodsMoney // 货品金额
          }));

          // 如果需要进一步处理 response 数据，可以在这里添加
          // 例如：
          this.total = response.total; // 总记录数
        })
        .catch(error => {
          console.error('请求失败:', error);
        });
    },

    handleReturnStock() {
      console.log('详情:' + this.XZTHqueryParams);
      listRejected(this.XZTHqueryParams)
        .then(response => {
          // // 使用 JSON.stringify 转换并美化输出
          console.log('后端响应:', JSON.stringify(response, null, 2));
          this.returnList = response.rows
          // // 假设 response.data 是一个数组，包含多个进货单信息
          // this.returnList = response.data.map(item => ({
          //   prId: item.prId,
          //   prCode: item.prCode,
          //   prState: item.prState,
          //   prTime: item.prTime,
          //   supplierName: item.supplierName, // 供应商名称
          //   supplierId: item.supplierId,
          //   phDept: item.phDept,// 进货部门名称
          //   contacts: item.contacts, // 进货人
          //   rejectedNum: item.rejectedNum, // 货品数量
          //   rejectedMoney: item.rejectedMoney // 货品金额
          // }));
          // 如果需要进一步处理 response 数据，可以在这里添加
          // 例如：
          this.THtotal = response.total; // 总记录数
        })
        .catch(error => {
          console.error('请求失败:', error);
        });
    },
    //进货订单搜索
    JHDDhandleQuery() {
      this.queryParams.pageNum = 1;
      // console.log("阿三大苏打城市达成:"+JSON.stringify(this.queryParams, null, 2))
      this.JHDDgetList();

    },
    //进货订单重置
    JHDDresetQuery() {
      this.queryParams.phCode = '';
      this.queryParams.phState = null;
      this.queryParams.supplierId = null;
      this.queryParams.phDate = null;
    },
    JHTHhandleQuery() {
      this.XZTHqueryParams.pageNum = 1;
      this.handleReturnStock();
    },
    //进货订单重置
    JHTHresetQuery() {
      this.XZTHqueryParams.srCode = '';
      this.XZTHqueryParams.srState = null;
      this.XZTHqueryParams.saleDate = null;
    },
    THsubmitForm() {
      // 此时确认至少有一个供应商选择
      this.pyInboundData.relatedNumber = this.phCodes.join(''); // 设置相关编号
      console.log("萨达安安:" + JSON.stringify(this.THselectList, null, 2))
      this.pyInboundData.customer = this.THselectList[0].customer
      this.pyInboundData.contactPerson = this.THselectList[0].contacts
      this.pyInboundData.contactPhone = this.THselectList[0].phone
      this.openReturnOrder = false;
    },
    //进货订单确定
    JHDDsubmitForm() {
      // 检查是否选择了供应商
      if (!this.phsupplierIds.length) {
        this.pyInboundData.supplierId = []; // 将供应商ID设置为空数组
        return; // 直接返回，不执行后面的代码
      }

      // 此时确认至少有一个供应商选择
      this.pyInboundData.relatedNumber = this.phCodes.join(''); // 设置相关编号
      this.pyInboundData.supplierId = this.phsupplierIds[0]; // 设置有效的ID

      // 继续调用获取供应商联系信息
      this.fetchSupplierContact(this.pyInboundData.supplierId);
      // if (this.pyInboundData.inventoryType === '0') {
      // 关闭采购订单窗口
      this.openPurchaseOrder = false;
      // } else if (this.pyInboundData.inventoryType === '1') {
      // 关闭采购订单窗口
      // this.openReturnOrder = false;
      // }


    },
    JHDDhandleSelectionChange(selection) {
      if (selection.length > 1) {
        // 如果选择超过一项，取消之前的选择
        this.$refs.table.clearSelection();
        this.$refs.table.toggleRowSelection(selection[selection.length - 1], true);
        selection = [selection[selection.length - 1]];
      } else if (selection.length === 0) {
        this.phCodes = []
        this.phsupplierIds = []
      }
      if (this.pyInboundData.inventoryType === '0') {
        this.phCodes = selection.map(item => item.phCode);
      } else if (this.pyInboundData.inventoryType === '1') {
        this.phCodes = selection.map(item => item.srCode);
        console.log("选中111:", selection);
        this.THselectList = selection
      }

      this.phsupplierIds = selection.map(item => item.supplierId);
      console.log("选中:", selection);

    },
    //换选入库类型清空信息
    handleInventoryTypeChange(newVal) {
      // 当入库类型改变时，重置相关数据
      this.pyInboundData.relatedNumber = null; // 设置相关编号
      this.RKMXtableData = [];
      if (this.pyInboundData.inventoryType !== '0') {
        this.pyInboundData.supplierId = null; // 设置有效的ID
      }

      this.pyInboundData.contactPerson = null; // 清除联系人
      this.pyInboundData.customer = null
      this.pyInboundData.contactPhone = null; // 清除联系人电话
    },
    //取消
    JHDDcancel() {
      this.pyInboundData.relatedNumber = null; // 设置相关编号
      this.pyInboundData.supplierId = null; // 设置有效的ID
      this.pyInboundData.contactPerson = null;
      this.pyInboundData.contactPhone = null; // 设置有效的ID
      if (this.pyInboundData.inventoryType === '0') {
        this.openPurchaseOrder = false;
      } else if (this.pyInboundData.inventoryType === '1') {
        this.openReturnOrder = false;
      }

    },
    //关联进货单号
    handleCheckboxChange() {
      selectAllOdPurchaseDetails(query)
        .then(response => {
          // console.log("获取货品信息:" + JSON.stringify(response.data, null, 2));

          // // 提取已存在于入库明细中的货品代码
          // const existingProductCodes = new Set(this.RKMXtableData.map(item => item.productCode));

          // // 设置过滤后的产品，勾选已经存在的货品
          // this.filteredProducts = response.data.map(product => ({
          //   ...product,
          //   selected: existingProductCodes.has(product.productCode)  // 检查是否存在于入库明细中
          // }));

          // // 在初始化时设置选中的产品
          // this.selectedProducts = this.filteredProducts.filter(product => product.selected);
          this.filteredProducts = response.rows.map((item) => ({
            ...item,
            isSelected: false,
            notStocked: item.notStocked
          }))
        })
        .catch(error => {
          console.error('获取信息失败:', error);
        });
    },
    OdPurchaseDetails() {
      const query = {
        phCodes: this.pyInboundData.relatedNumber,
        productCode: this.JHMXqueryParams.productCode
      };
      // console.log("进货订单:" + this.pyInboundData.relatedNumber);

      selectAllOdPurchaseDetails(query)
        .then(response => {
          // console.log("获取货品信息:" + JSON.stringify(response.data, null, 2));

          // 提取已存在于入库明细中的货品代码
          const existingProductCodes = new Set(this.RKMXtableData.map(item => item.productCode));

          // 设置过滤后的产品，勾选已经存在的货品
          this.filteredProducts = response.rows.map(product => ({
            ...product,
            selected: existingProductCodes.has(product.productCode)  // 检查是否存在于入库明细中
          }));
          this.MXtotal = response.total;
          // 在初始化时设置选中的产品
          this.selectedProducts = this.filteredProducts.filter(product => product.selected);
        })
        .catch(error => {
          console.error('获取信息失败:', error);
        });
    },
    RejectedDetailsList() {
      // this.THMXqueryParams.srCode = this.pyInboundData.relatedNumber
      const query = {
        srCode: this.pyInboundData.relatedNumber,
        productCode: this.THMXqueryParams.productCode
      };
      // console.log("退货:" + JSON.stringify(this.THMXqueryParams, null, 2))

      selectOdSaleRejectedDetailsList(query)
        .then(response => {
          // console.log("获取货品信息1144:" + JSON.stringify(response, null, 2));
          this.filteredReturnProducts = response.rows;
          // // 提取已存在于入库明细中的货品代码
          // const existingProductCodes = new Set(this.RKMXtableData.map(item => item.productCode));

          // // 设置过滤后的产品，勾选已经存在的货品
          // this.filteredProducts = response.data.map(product => ({
          //   ...product,
          //   selected: existingProductCodes.has(product.productCode)  // 检查是否存在于入库明细中
          // }));

          // // 在初始化时设置选中的产品
          // this.selectedProducts = this.filteredProducts.filter(product => product.selected);
          this.MXTHtotal = response.total;
        })
        .catch(error => {
          console.error('获取信息失败:', error);
        });
    },

    //入库明细添加按钮
    RKMXopenDialog() {
      if (this.pyInboundData.inventoryType === '0') {
        this.openInventoryDetails = true;
        this.OdPurchaseDetails();
      } else if (this.pyInboundData.inventoryType === '1') {

        this.openReturnInventoryDetails = true;
        this.RejectedDetailsList();


      }

    },
    //进货入库明细搜索
    RKMXhandleQuery() {
      console.log("萨达安安:" + JSON.stringify(this.JHMXqueryParams, null, 2))
      this.JHMXqueryParams.pageNum = 1;
      this.OdPurchaseDetails()

      this.selectedItems.clear() // 清空临时选择
    },
    // JHDDMX() {
    //   this.JHMXqueryParams.phCodes = this.pyInboundData.relatedNumber
    //   selectAllOdPurchaseDetails(this.JHMXqueryParams)
    //     .then(response => {
    //       // console.log("萨达安安:" + JSON.stringify(response.data, null, 2))
    //       this.filteredProducts = response.data
    //     })
    //     .catch(error => {
    //       console.error('获取信息失败:', error);
    //     });
    // },
    //退货入库明细搜索
    THMXhandleQuery() {
      this.THMXqueryParams.pageNum = 1;
      this.RejectedDetailsList
      this.selectedItems.clear() // 清空临时选择
      // this.THMXqueryParams.srCode = this.pyInboundData.relatedNumber
      // console.log("萨达安安:" + JSON.stringify(this.THMXqueryParams, null, 2))
      // selectOdSaleRejectedDetailsList(this.THMXqueryParams)
      //   .then(response => {
      //     // console.log("萨达安安:" + JSON.stringify(response.data, null, 2))
      //     this.filteredReturnProducts = response.data
      //   })
      //   .catch(error => {
      //     console.error('获取信息失败:', error);
      //   });
    },
    THMXhresetQuery() {

    },
    setSelection() {
      this.$refs.table.clearSelection(); // 清空之前的选择
      this.filteredProducts.forEach(item => {
        const isSelected = this.selectedProducts.some(selected => selected.phDetailsId === item.phDetailsId);
        this.$refs.table.toggleRowSelection(item, isSelected);
      });
    },
    handleSingleSelect(val, row) {
      if (val) {
        this.selectedItems.add(row)
      } else {
        this.selectedItems.delete(row)
      }
      if (this.pyInboundData.inventoryType === '0') {
        // 触发选择变更事件
        this.JHMXhandleSelectionChange(Array.from(this.selectedItems))
      } else if (this.pyInboundData.inventoryType === '1') {
        this.THMXhandleSelectionChange(Array.from(this.selectedItems))
      }

    },
    JHMXhandleSelectionChange(selection) {
      console.log("选:", selection);
      this.selectedProducts = selection;

    },
    THMXhandleSelectionChange(selection) {
      console.log("选:", selection);
      this.selectedProducts = selection;
    },

    RKMXresetQuery() {

    },
    THMXsubmitForm() {
      // 只添加选中的货品到入库表
      this.selectedProducts.forEach(product => {
        // 检查是否已存在
        const exists = this.RKMXtableData.some(item => item.phDetailsId === product.rdId); // 使用 phDetailsId 和 rdid 进行比较
        if (!exists) {
          // 映射 selectedProducts 中的字段到 RKMXtableData 的格式
          this.RKMXtableData.push({
            phDetailsId: product.srDetailsId, // 将 rdid 映射为 phDetailsId
            productCode: product.productCode,
            productName: product.productName,
            productModel: product.productModel,
            productType: product.productType,
            unit: product.unit,
            currentStock: product.currentStock,
            alreadyNum: product.alreadyNum,
            notStocked: product.notStocked,
            salePrice: product.salePrice,
            rejectedNum: product.rejectedNum,
            // 其他需要的字段
            quantityThisTime: null // 用于输入数量
          });
          this.addedItemCodes.add(product.productCode)
        }
      });
      // 检查是否有新选择的货品
      const newItems = Array.from(this.selectedItems)
      if (newItems.length === 0) {
        this.$modal.msgWarning('请选择要添加的货品！')
        return
      }
      // 检查新选择的货品是否已存在
      const duplicateItems = newItems.filter((item) =>
        this.addedItemCodes.has(item.itemCode)
      )
      if (duplicateItems.length > 0) {
        this.$modal.msgWarning('已存在相同的货品，请勿重复添加！')
        return
      }
      console.log("更新后的入库产品:", this.RKMXtableData);
      this.selectedItems.clear()
      this.openReturnInventoryDetails = false;  // 关闭对话框
    },
    RKMXsubmitForm() {
      // 只添加选中的货品到入库表
      this.selectedProducts.forEach(product => {
        // 检查是否已存在
        const exists = this.RKMXtableData.some(item => item.productCode === product.productCode);
        if (!exists) {
          this.RKMXtableData.push({
            ...product,
            quantityThisTime: null, // 确保您进行数量输入时的字段准备


          });
          this.addedItemCodes.add(product.productCode)
        }
      });
      // 检查是否有新选择的货品
      const newItems = Array.from(this.selectedItems)
      if (newItems.length === 0) {
        this.$modal.msgWarning('请选择要添加的货品！')
        return
      }
      // 检查新选择的货品是否已存在
      const duplicateItems = newItems.filter((item) =>
        this.addedItemCodes.has(item.itemCode)
      )
      if (duplicateItems.length > 0) {
        this.$modal.msgWarning('已存在相同的货品，请勿重复添加！')
        return
      }
      console.log("更新后的入库产品:", this.RKMXtableData);
      this.selectedItems.clear()
      this.openInventoryDetails = false;  // 关闭对话框
    },

    //入库明细最终表格
    deleteRow(item) {
      // console.log("rows:"+rows.productCode)
      // rows.splice(index, 1);
      this.RKMXtableData = this.RKMXtableData.filter(
        (currentItem) => currentItem.productCode !== item.productCode
      )
      this.addedItemCodes.delete(item.productCode) // 从已添加集合中移除
    },
    // 多选框选中数据
    RKMXhandleSelectionChange(selection) {
      console.log("选中:" + JSON.stringify(selection, null, 2))

      // // this.ids = selection.map(item => item.inventoryId)
      // // this.single = selection.length !== 1
      // // this.multiple = !selection.length
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    fetchwhLocationContact(selectedLocation, productCode, currentRow) {
      // console.log("选中的库位:", selectedLocation);
      // console.log("货品编号:", productCode); // 访问当前行的货品编号

      const query = {
        location: selectedLocation,
        productCode: productCode
      };

      // 调用 API 查询库存
      selectWhInventoryByCode(query)
        .then(response => {
          console.log("库存:" + JSON.stringify(response.data, null, 2));

          // 假设 response.data 是一个数组，我们只关心第一个元素
          if (response.data.length > 0) {
            const inventoryData = response.data[0];
            // 直接更新当前行的 currentStock
            this.$set(currentRow, 'currentStock', inventoryData.currentInventory); // 更新当前行的 currentStock
            console.log("更新后的当前库存:", currentRow.currentStock); // 打印更新后的库存
          } else {
            console.log("没有找到库存数据");
            // 如果没有找到，可以考虑将 currentStock 设置为空或者提示用户
            this.$set(currentRow, 'currentStock', 0); // 更新当前行的 currentStock
          }
        })
        .catch(error => {
          console.error('查询库存失败:', error);
        });
    },
    validateQuantity(row) {
      const enteredQuantity = Number(row.quantityThisTime);
      const notStockedQuantity = Number(row.notStocked);

      if (enteredQuantity > notStockedQuantity) {
        this.$message.error('不允许大于未入库数量！');
        row.quantityThisTime = notStockedQuantity; // 可选：将输入框的值重置为未入库数量
      }
    },
    uploadChange(file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      // 定义允许的文件类型
      const allowedTypes = ['application/msword', 'application/pdf', 'application/x-rar-compressed', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
      // 检查文件类型是否在允许的类型中
      const isAllowedType = allowedTypes.includes(file.type);
      // 检查文件大小是否不超过200MB (200 * 1024 * 1024 bytes)
      const isLt200M = file.size <= 200 * 1024 * 1024;

      if (!isAllowedType) {
        this.$message.error('上传文件只能是 doc, pdf, rar 格式!');
      }
      if (!isLt200M) {
        this.$message.error('上传文件大小不能超过 200MB!');
      }
      return isAllowedType && isLt200M;
    }


  }



}
</script>
<style>
i>.el-icon-check {
  font-size: 16px;
  font-weight: bold;
}

.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 100px;

  right: 0;
  padding-left: 1400px;
  padding-top: 20px;
  background-color: #f4f4f4;
  /* 设置底部背景色 */
  z-index: 1000;
  /* 确保底部不被遮挡 */
}

.jcxx {
  margin-top: 20px;

}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
  margin-top: 20px;
}

.total-row {
  background-color: #f9f9f9;
  /* 背景色 */
  font-weight: bold;
  /* 粗体 */
}

.label {
  color: black;
  /* 标签字体颜色 */
  margin-left: 10px;
}

.you {
  margin-left: 930px;
}

.value {
  color: rgb(227, 139, 50);
  /* 数字字体颜色 */
}

/* 如果需要调整对齐方式，可以添加其他样式 */
.total-row td {
  text-align: left;
  /* 左对齐 */
}

.total-row td:last-child {
  text-align: right;
  /* 最后一列右对齐 */
}

/* 添加样式以美化绿色对勾 */
</style>
